package api.apiservice.apiopenplat.Utils;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;

/**
 *
 * http调用工具类
 *
 * */
public class HttpUtils {

    /**
     *
     * Http get请求 返回状态码
     *
     * */
    public static String requestByGet(String url){
        JSONObject jsonObject = JSONUtil.parseObj(HttpUtil.get(url));
        return jsonObject.getStr("code");
    }


    /**
     *
     *
     * Http get请求 返回内容
     *
     * */
    public static String requestByGet(String url , ArrayList<String> parmas){
        return HttpUtil.get(url, CharsetUtil.CHARSET_UTF_8);
    }

    /**
     *
     * Http post请求 返回内容
     *
     * */
    public static String requestByPost(String url,String paramName,Object data){
        //传参
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put(paramName,data);
        return  HttpUtil.post(url, paramMap);
    }


    /**
     *
     *
     * Http调用  生成HttpRequest
     *
     * */
    public static HashMap<String,String> generatorRequest(long timeDifference,String accessKey ,String accessSecret,long userId){
        HashMap<String,String> paramMap = new HashMap<>();
        //唯一ID
        String onlyId = IdUtil.simpleUUID();
        paramMap.put("accessKey",accessKey);
        paramMap.put("accessSecret",accessSecret);
        paramMap.put("onlyId",onlyId);
        paramMap.put("timeDifference",String.valueOf(timeDifference));
        paramMap.put("username",String.valueOf(userId));
        return paramMap;
    }


    public static  HttpServletResponse appendHeader(HttpServletResponse response, HashMap<String,String> headerParams){
        response.addHeader("accessKey",headerParams.get("accessKey"));
        response.addHeader("onlyId",headerParams.get("onlyId"));
        response.addHeader("timeDifference",headerParams.get("timeDifference"));
        response.addHeader("username",headerParams.get("username"));
        return response;
    }


    /**
     *
     * 通过Get方式发送请求
     *
     * */
    public static HttpResponse requestByGet(String url,HashMap<String,String> responseMap){

        HttpResponse httpResponse = HttpRequest.get(url).addHeaders(responseMap).execute();

        return httpResponse;
    }

}
